<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;

class Timer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'timer';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时器';

    /**
     * 操作
     */
    public function handle()
    {
        self::tick();
    }

    /**
     * 获取毫秒数
     * @param int $second (秒数)
     * @return float
     */
    private function getMillisecond($second = 0)
    {
        list($t1, $t2) = explode(' ', microtime());
        return (int)sprintf('%.0f',((floatval($t1)+floatval($t2))+(floatval($second)))*1000);
    }

    /**
     * 获取剩余的微妙数
     * @param int $second (秒数)
     * @return int
     */
    private function getSurplusMillisecond($second = 0)
    {
        return (int)(self::getMillisecond($second)-self::getMillisecond());
    }

    /**
     * 该定时器会每隔指定时间触发回调函数的执行
     */
    public function tick()
    {
        echo "当前时间是:".date('Y-m-d H:i:s',time())."\n";
        //12点准时艾特我
        \Swoole\Timer::tick(self::getSurplusMillisecond(1*60),function (){
            $time = date('Y-m-d H:i:s',time());
            echo "当前时间是:{$time}\n";
        });
    }

    /**
     * 只执行一次，之后执行完成后就会销毁
     * @param int $afterTime
     */
    public function after($afterTime=3000)
    {
        \Swoole\Timer::after($afterTime, function () {
            echo "Laravel 也很棒\n";
        });
    }

    /**
     * 设置定时器，清除定时器
     */
    public function clear()
    {
        $count = 0;
        \Swoole\Timer::tick(1000, function ($timerId, $count) {
            global $count;
            echo "Swoole 很棒\n";
            $count++;
            if ($count == 3) {
                \Swoole\Timer::clear($timerId);
            }
        }, $count);
    }
}